from django.shortcuts import render
from .models import *
from rest_framework.response import Response
from rest_framework.views import APIView
from .ser import *
# Create your views here.
import re

class UserM(APIView):
    def post(self,request):
        ser = Userser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code':20010})

class Usermanage(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        if user:
            if user.password==password:
                return Response({'code':200,'userid':user.id})
            else:
                return Response({'code':20010,'meg':'密码错误'})
        else:
            return Response({'code':20011,'meg':'用户不存在'})


class NewsM(APIView):
    def post(self,request):
        ser  = Newser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})

    def get(self,request):
        id = request.GET.get('id')
        se = News.objects.filter(id=id).all()
        ser = Newser(se,many=True)
        return Response({'code':200,'list':ser.data})


class Newsmanage(APIView):
    def get(self,request):
        id = News.objects.all()
        ser = Newser(id,many=True)
        return Response({'code':200,'list':ser.data})


